package com.zhdl.modules.wallpulley.web;

import cn.hutool.core.util.HexUtil;
import com.project.common.util.DelayUtil;
import com.zhdl.common.ytools.HexToBitTools;
import com.zhdl.common.ytools.HttpClientUtil;
import com.zhdl.common.ytools.IntToHexUtil;
import com.zhdl.hardware.motor.leisai.repository.impl.LeisaiPortCmdHandleDaoImpl;
import com.zhdl.hardware.motor.leisai.service.LSCmdSendService;
import com.zhdl.hardware.plc.siemens.exc.SiemensPortReceiveHandelImpl;
import com.zhdl.hardware.plc.siemens.service.SiemensCmdSendService;
import com.zhdl.modules.common.entity.ProcessRecords;
import com.zhdl.modules.common.service.ProcessRecordsService;
import com.zhdl.modules.common.service.ProcessWarnService;
import com.zhdl.modules.wallpulley.entity.AllDatePoint;
import com.zhdl.modules.wallpulley.entity.DatePoint;
import com.zhdl.modules.wallpulley.entity.EventRecords;
import com.zhdl.modules.wallpulley.entity.ParameterSettings;
import com.zhdl.modules.wallpulley.service.TensileDistanceService;
import com.zhdl.modules.wallpulley.web.req.CalibrationParam;
import com.zhdl.modules.wallpulley.web.resp.*;
import com.zhdl.network.service.BatteryRS485;
import com.zhdl.network.service.impl.BatteryRS485Impl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.ScheduledFuture;

@Slf4j
@Component
public class WallPulleyProcess {

    @Resource
    public ThreadPoolTaskScheduler taskScheduler1;

    public ScheduledFuture<?> scheduledFuture;

    Map<String, ScheduledFuture<?>> mapSF = new HashMap<>();

    /**
     * 当前流程是否在运行 - 默认未运行
     * 当前流程是否在测试 - 默认未测试
     * true 运行 false 未运行
     */
    public boolean isRunning = false, isTest = false;

    /**
     * PLC -拉力对应值 && 拉力刚合点
     */
    public int plcValue = 0;
    public int lastPoint1 = 0, lastPoint2 = 0, lastPoint3 = 0;
    /**
     * 当前 电机距离-拉力 对应
     */
    public List<TensileDistanceResp> memoryCompare = new ArrayList<>();
    public TensileDistanceResp tdResp = new TensileDistanceResp();
    public TensileDistanceSseResp tdRespSse = new TensileDistanceSseResp();
    public List<DatePointResp> datePointResps = new ArrayList<>();
    public List<DatePointResp> datePointRespsAll = new ArrayList<>();
    /**
     * 电机流程
     */
    public int motorProcess = -1;
    public boolean isSelfChecking, SelfCheckingOK = false, isWarnStatus = false;
    public boolean batterySelfCheck = false, plcSelfCheck = false, motorSelfCheck = false;
    /* 1为正常 */
    public StringBuffer warnList = new StringBuffer("00000-");
    /* 报警内容步数 */
    public int contentStep = 0;
    /**
     * battery 电池🔋电量 &&& 电池🔋状态
     */
    String batteryCom1 = "100%", batteryStatus = "0";
    EventRecordsResp erResp = new EventRecordsResp();
    MeasurementDataResp mdResp = new MeasurementDataResp();
    ParameterSettingsResp psResp = new ParameterSettingsResp();

    /**
     * 电机预计距离
     * 电机当前位置
     */
    private int motorDistance = 0, motorLocation = 0;

    @Resource
    BatteryRS485Impl batteryRS485Init;
    @Resource
    @Qualifier("SiemensReceiveSendServiceImpl")
    public SiemensCmdSendService siemensReceiveHandelDao;
    @Resource
    private LSCmdSendService lsCmdSendService;
    @Resource
    private BatteryRS485 batteryRS485;
    @Resource
    public TensileDistanceService tensileDistanceService;
    @Resource
    private LeisaiPortCmdHandleDaoImpl cmdHandleDao;
    @Resource
    private SiemensPortReceiveHandelImpl siemensPortReceiveHandel;
    @Resource
    private ProcessRecordsService processRecordsService;
    @Resource
    private ProcessWarnService processWarnService;

    /* 保存刚合点次数 */
    public int extractedTimes = 0;


    public void release() {
        extractedTimes=0;
        motorProcess = -1;
        motorDistance = 0;
        motorLocation = 0;
        plcValue = 0;
        tdResp = new TensileDistanceResp();
        tdRespSse = new TensileDistanceSseResp();
        memoryCompare = new ArrayList<>();
        mdResp = new MeasurementDataResp();
        erResp = new EventRecordsResp();
        psResp = new ParameterSettingsResp();
        isRunning = false;
        releasePoint();

        ProcessRecords byId = processRecordsService.findById(1);
        byId.setProcessStep(0);
        processRecordsService.saveProcessDao(byId);
    }

    public void releasePoint() {
        lastPoint1 = 0;
        lastPoint2 = 0;
        lastPoint3 = 0;
    }

    public void releaseBackOrigin() {
        release();
        lsCmdSendService.cancelScheduledFuture();
    }

    /**
     * 初始化
     */
    public void init() {
        /*
            1. 初始化 电池串口
            2. 初始化 电机串口
            3. 初始化 西门子2000网口
         */
        batteryRS485Init.init();
        cmdHandleDao.addPort("2");
        siemensPortReceiveHandel.addPort("0000");

        /*
            1. 检查开机是否需要自检
         */
        ProcessRecords byId = processRecordsService.findById(1);
        isSelfChecking = byId.isSelfChecking();
        tdRespSse.setSelfCheckStart(isSelfChecking);

        /*
            电池-开启一直读取电池电量
         */
        taskScheduler1.scheduleWithFixedDelay(() -> batteryRS485.readInfo(s -> {
            String bs = s.substring(0, 4);
            String b = s.substring(4, 8);
            int i = HexUtil.hexToInt(b);
            int i1 = HexUtil.hexToInt(bs);
            log.info("当前电量为:" + i);
            if (bs.startsWith("FF")) {
                batteryStatus = "0";
            }
            if (bs.startsWith("00")) {
                batteryStatus = "1";
            }
            if (i1 == 0) {
                batteryStatus = "0";
            }
            log.info("当前充电状态为:" + batteryStatus);
            if (i >= 1500) {
                tdResp.setBattery("100%");
                tdRespSse.setBattery("100%");
                tdRespSse.setBatteryStatus(batteryStatus);
                log.info("当前电量: 100%");
            } else {
                String battery = ((int) ((i / 1500.00) * 100)) + "%";
                tdResp.setBattery(battery);
                tdRespSse.setBattery(battery);
                tdRespSse.setBatteryStatus(batteryStatus);
                batteryCom1 = battery;
                log.info("当前电量: " + battery);
            }
            if (((int) ((i / 1500.00) * 100)) < 30) {
                log.info("当前电量低于30");
            }
            batterySelfCheck = true;
            log.info("通讯-电池通讯正常");
        }), 10000);
        /*
            西门子-开启一直读PLC拉力值
         */
        taskScheduler1.scheduleWithFixedDelay(() -> {
            siemensReceiveHandelDao.siemensAddressValue("0000", "0", "0000", 6, 20, s -> {
                /* 流程-当前流程运行状态 */
                tdRespSse.setWallPulleyStatus(isRunning);

                /* 设置 plc 自检 */
                plcSelfCheck = true;
                tdRespSse.setSelfCheckOK(SelfCheckingOK);

                log.info("通讯-西门子通讯正常");

                /* 8，16 拉力值寄存器 */
                String substring34 = s.substring(8, 16);
                int temp = IntToHexUtil.hexToSignInt(substring34);
                /* 拉力值补充 */
                temp = temp + (218714) - (180000) + (171000);
                if (calibrationIsOk){
                    temp = temp - calibrationPlcValue;
                }
//                temp = temp + (218714) -(180000);
                plcValue = temp;

                /* 0，4 刚合点寄存器值 */
                String substring1 = s.substring(0, 4);
                /* 转换为 2进制 bit位数 */
                String bitValueByHex = HexToBitTools.readBitValueByHex(substring1);
                log.info("bitValueHex--->{}", bitValueByHex);
                String stop = bitValueByHex.substring(0, 1);
                String bit1 = bitValueByHex.substring(1, 2);
                String bit2 = bitValueByHex.substring(2, 3);
                String bit3 = bitValueByHex.substring(3, 4);

                /* 物理按钮-急停 */
                if (stop.equals("1")){
                    siemensReceiveHandelDao.siemensWriteValue("0000","1","0000","0000");
                    lsCmdSendService.leisaiEmergencyStop("2", "01");
                    release();
                }

                /* 三个刚合点的状态-> 0800  0C00 0E00 */
                DatePointResp datePointResp = new DatePointResp();
                /* 只要有一个刚合点为1，则判断 */
                if (bit1.equals("1")) {
                    if (lastPoint1 == 0) {
                        lastPoint1 = 1;
                        isDatePoint = true;
                        datePointResp.setDatePointAChange(1);
                        datePointResp.setDataPointA(1);
                        extracted(datePointResp);
                    }
                } else {
                    if (lastPoint1 == 1) {
                        lastPoint1 = 0;
                        isDatePoint = false;
                        datePointResp.setDatePointAChange(10);
                        datePointResp.setDataPointA(1);
                        extracted(datePointResp);
                    }
                }
                if (bit2.equals("1")) {
                    if (lastPoint2 == 0) {
                        lastPoint2 = 1;
                        isDatePoint = true;
                        datePointResp.setDatePointBChange(1);
                        datePointResp.setDataPointB(1);
                        extracted(datePointResp);
                    }
                } else {
                    if (lastPoint2 == 1) {
                        lastPoint2 = 0;
                        isDatePoint = false;
                        datePointResp.setDatePointBChange(10);
                        datePointResp.setDataPointB(1);
                        extracted(datePointResp);
                    }
                }
                if (bit3.equals("1")) {
                    if (lastPoint3 == 0) {
                        lastPoint3 = 1;
                        isDatePoint = true;
                        datePointResp.setDatePointCChange(1);
                        datePointResp.setDataPointC(1);
                        extracted(datePointResp);
                    }
                } else {
                    if (lastPoint3 == 1) {
                        lastPoint3 = 0;
                        isDatePoint = false;
                        datePointResp.setDatePointCChange(10);
                        datePointResp.setDataPointC(1);
                        extracted(datePointResp);
                    }
                }

                if (isDatePoint){
                    datePointResp.setDatePointAChange(0);
                    datePointResp.setDatePointBChange(0);
                    datePointResp.setDatePointCChange(0);
                    datePointResp.setDataPointA(0);
                    datePointResp.setDataPointB(0);
                    datePointResp.setDataPointC(0);
                    extracted(datePointResp);
                }

                if (calibrationIsRun && !calibrationIsOk){
                    plcValueList.add(plcValue);
                }

//                findMaxPlcValueByType(plcValue);

//                if (
//                        (bit1.equals("1") && lastPoint1 == 1) || (bit2.equals("1") && lastPoint2 == 1) || (bit3.equals("1") && lastPoint3 == 1) ||
//                        (bit1.equals("0") && lastPoint1 == 0) || (bit2.equals("0") && lastPoint2 == 0) || (bit3.equals("0") && lastPoint3 == 0)
//                ) {
//                    //保存
//                }

                log.info("当前拉力值为------>{}原始拉力值->{}", plcValue, temp - 218714 + 18000);
                log.info("bit1->{}bit2->{}bit3->{}lastPoint1->{}lastPoint2->{}lastPoint3->{}dataPoint1->{}dataPoint2->{}dataPoint3->{}"
                        , bit1, bit2, bit3, lastPoint1, lastPoint2, lastPoint3, 0, 0, 0);
            });
        }, 20);

        /* 电机-设置默认电机速度 */
        lsCmdSendService.leisaiSetMoveSpeed("2", "01", 200);

        /* 电机-读取报警信息 */
        getAlarmMessage();

        /* 自检 */
        compareStatus(0);
    }

    public boolean isDatePoint = false;

    int plcMaxValue1 = Integer.MIN_VALUE , plcMaxValue3 = Integer.MIN_VALUE ;
    int plcMaxValue2 = Integer.MAX_VALUE , plcMaxValue4 = Integer.MAX_VALUE ;

    public void findMaxPlcValueByType(int plcValue){
        if (motorProcess == 1){
            if (plcValue > plcMaxValue1) {
                plcMaxValue1 = plcValue; // 更新找到点之前的最大值
            }
        } else if (motorProcess == 2){
            if (plcValue < plcMaxValue1) {
                plcMaxValue2 = plcValue; // 更新找到点之前的最大值
            }
        } else if (motorProcess == 3){
            if (plcValue > plcMaxValue1) {
                plcMaxValue3 = plcValue; // 更新找到点之前的最大值
            }
        } else if (motorProcess == 4){
            if (plcValue < plcMaxValue1) {
                plcMaxValue4 = plcValue; // 更新找到点之前的最大值
            }
        }
    }



    private void extracted(DatePointResp datePointResp) {
        extractedTimes++;
        log.info("extractedTimes-->{}", extractedTimes);

        /* 保存这一刻的时间 */
        Instant now = Instant.now();
        long currentTimestamp = now.toEpochMilli();
        LocalDateTime localDateTime = LocalDateTime.now();
        String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

        /* 获取类型 */
        String type = switch (motorProcess) {
            case 1 -> "1";
            case 2 -> "2";
            case 3 -> "3";
            case 4 -> "4";
            default -> "-1";
        };

        if (!type.equals("-1")){

            /* 计算出电机的偏差位置 */
            long motorLongTime = tdRespSse.getNowLongTime();
            long difference = currentTimestamp - motorLongTime;
            /* 速度 / 60s / 1000ms  = 每毫秒的运行距离  通过齿轮比 5//7 得出每毫秒运行的距离 */
            double msMotorRun = (400.00 / 60 / 1000) * 5  / 7;
            double motorDifferenceDistance = difference * msMotorRun;

            /* 计算出不同类型所需要的数据 */
            double motorDis = tdRespSse.getDistanceValue();
            if (type.equals("1") || type.equals("3")){
                motorDis = tdRespSse.getDistanceValue() + motorDifferenceDistance;
            } else {
                motorDis = tdRespSse.getDistanceValue() - motorDifferenceDistance;
            }

            /*
             * 保存刚合点List
             */
            /* 计算时间差，求距离 */
            datePointResp.setNowTime(format);
            datePointResp.setNowLongTime(currentTimestamp);
            /* 类型 - 电机偏差 电机距离  - plc值 拉力值  */
            datePointResp.setType(type);
            datePointResp.setDistanceValue(motorDis);
            datePointResp.setTensileValue(plcValue / 1000.00);
            datePointResps.add(datePointResp);

            /*
                保存数据到List存入数据库
             */
            TensileDistanceResp tensileDistanceResp = new TensileDistanceResp();
            tensileDistanceResp.setNowTime(format);
            tensileDistanceResp.setNowLongTime(currentTimestamp);

            /* 获取刚合点 及其变化 */
            tensileDistanceResp.setDataPointA(datePointResp.getDataPointA());
            tensileDistanceResp.setDataPointB(datePointResp.getDataPointB());
            tensileDistanceResp.setDataPointC(datePointResp.getDataPointC());
            tensileDistanceResp.setDatePointAChange(datePointResp.getDatePointAChange());
            tensileDistanceResp.setDatePointBChange(datePointResp.getDatePointBChange());
            tensileDistanceResp.setDatePointCChange(datePointResp.getDatePointCChange());

            /* 反推回脉冲数 - 方便计算 */
            tensileDistanceResp.setType(type);
            double v = (motorDis * 7 / 5) * 10000;
            tensileDistanceResp.setDistanceValue((int) v);
            tensileDistanceResp.setTensileValue(plcValue);

            if (type.equals("1") || type.equals("3")){
                if (motorDis >= 41.00){
                    memoryCompare.add(tensileDistanceResp);
                }
            } else {
                if (motorDis <= 80.00){
                    memoryCompare.add(tensileDistanceResp);
                }
            }
        }

    }

    public TDRunResultResp tdRunResultResp = new TDRunResultResp();

    public int modelZero = 0;

    /**
     * 流程开始入口
     */
    public void WallPulleyProcessStart(int modelId) {

        /*
            判断是否是在调试状态 如果在就退出流程
         */
        if (isRunning) {
            return;
        }
        isRunning = true;


        datePointResps = new ArrayList<>();
        tdRunResultResp = new TDRunResultResp();

        /*
            写入轴运行状态为 1
         */
        siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0100");

        log.info("------------------流程开始运动------------------");
        /*
            读取数据库型号
         */
        ParameterSettings parameterById = tensileDistanceService.findParameterById(modelId);

        modelZero = parameterById.getModelZero();

        /* 设置电机运行和模式 */
        lsCmdSendService.leisaiSetMotorModel("2", "01", 1);
        /* 电机运动距离 = （数据库）实际距离+空行程 */
        motorDistance = parameterById.getModelDistance() + parameterById.getModelEmpty();

//        motorDistance = motorDistance + modelZero;

        /*
            运行速度
         */
        int modelSpeed = parameterById.getModelSpeed();
        lsCmdSendService.leisaiSetMoveSpeed("2", "01", modelSpeed);

        /*
            1. 流程开始则新建事务
            2. 新建事务详情
         */
        erResp.setModelId(modelId);
        erResp.setRecordResult("");
        int erId = tensileDistanceService.saveEventRecords(erResp);
        mdResp.setEventId(erId);

        /*
            流程开始运动
         */
        ProcessRecords byId = processRecordsService.findById(1);
        motorProcess = byId.getProcessStep();
        motorProcess = 0;
        nextIntMotor();
    }

    /**
     * 电机开始运动
     */
    public void nextIntMotor() {
        motorProcess++;

        /* 每次进来 保存流程 */
        ProcessRecords byId = processRecordsService.findById(1);
        byId.setProcessStep(motorProcess);
        processRecordsService.saveProcessDao(byId);

        switch (motorProcess) {
            case 1 -> {
                lsCmdSendService.leisaiReadCurrentLocation("2", "01", s -> {
                    /* 获取当前时间 */
                    LocalDateTime localDateTime = LocalDateTime.now();
                    String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                    Instant now = Instant.now();
                    long currentTimestamp = now.toEpochMilli();

                    /*
                        拉力-距离对应
                     */
                    TensileDistanceResp tdResp = new TensileDistanceResp();
                    TensileDistanceSseResp tdRespSse = new TensileDistanceSseResp();

                    /* 获取当前运动次数 */
                    if (motorProcess == 1) {
                        tdResp.setType("1");
                        tdRespSse.setType("1");
                    } else if (motorProcess == 2) {
                        tdResp.setType("2");
                        tdRespSse.setType("2");
                    } else if (motorProcess == 3) {
                        tdResp.setType("3");
                        tdRespSse.setType("3");
                    } else if (motorProcess == 4) {
                        tdResp.setType("4");
                        tdRespSse.setType("4");
                    } else {
                        tdResp.setType("-1");
                        tdRespSse.setType("-1");
                    }
                    log.info("当前为第几段运动{}", tdResp.getType());

                    /* 设置当前状态和运行时间 */
                    tdRespSse.setWallPulleyStatus(isRunning);
                    tdRespSse.setNowTime(format);
                    tdRespSse.setNowLongTime(currentTimestamp);
                    tdResp.setNowTime(format);
                    tdResp.setNowLongTime(currentTimestamp);

                    /* 获取电机当前位置 */
                    try{
                        motorLocation = Integer.parseInt(s, 16);
                    }catch (NumberFormatException numberFormatException){
                        log.info("保持上一次的电机位置:{}", motorLocation);
                    }

//                    if ()

                    tdResp.setDistanceValue(motorLocation);
                    tdResp.setTensileValue(plcValue);
                    /* Sse数据修改为--> 毫米单位 拉力更新*/
                    tdRespSse.setDistanceValue((((motorLocation / 10000.00) * 5) / 7));
                    tdRespSse.setTensileValue(plcValue / 1000.00);

                    log.info("当前电机位置为Hex--->{}", s);
                    log.info("当前Motor实时距离，——————》{}", (((motorLocation / 10000.00) * 5) / 7));
                    log.info("当前plc实时拉力，——————》{}", this.tdRespSse.getTensileValue());

                    if (!tdResp.getType().equals("-1")){
                        String type = tdResp.getType();
                        if (type.equals("1") || type.equals("3")){
                            if (tdRespSse.getDistanceValue() >= 41.00){
                                memoryCompare.add(tdResp);
                            }
                        } else {
                            if (tdRespSse.getDistanceValue() <= 80.00){
                                memoryCompare.add(tdResp);
                            }
                        }
                    }
                    this.tdResp = tdResp;

                    tdRespSse.setWorkOrderNumber(workOrderNumber);
                    tdRespSse.setPowerStationName(powerStationName);
                    tdRespSse.setIntervalNumber(intervalNumber);

                    tdRespSse.setBattery(batteryCom1);
                    tdRespSse.setBatteryStatus(batteryStatus);
                    this.tdRespSse = tdRespSse;

                    /* 设置 当前刚合点 状态 */
                    tdResp.setDataPointA(0);
                    tdResp.setDataPointB(0);
                    tdResp.setDataPointC(0);
                    tdRespSse.setDataPointA(0);
                    tdRespSse.setDataPointB(0);
                    tdRespSse.setDataPointC(0);
                });
                lsCmdSendService.leisaiSetMoveDist("2", "01", motorDistance);
                scheduledFuture = taskScheduler1.scheduleWithFixedDelay(() -> {
                    if (motorLocation >= motorDistance - 100 && motorLocation <= motorDistance + 100) {
                        scheduledFuture.cancel(true);
                        DelayUtil.delayedExecution(1000, () -> {
                            nextIntMotor();
                            log.info("雷赛电机-下降完成-one");
                        });
                    }
                }, 100);
            }
            case 2 -> {
                datePointRespsAll.addAll(datePointResps);
                datePointResps = new ArrayList<>();
                lsCmdSendService.leisaiSetMoveDist("2", "01", modelZero);
                scheduledFuture = taskScheduler1.scheduleWithFixedDelay(() -> {
                    if (motorLocation >= modelZero-100 && motorLocation <= modelZero+100) {
                        scheduledFuture.cancel(true);
                        DelayUtil.delayedExecution(1000, () -> {
                            nextIntMotor();
                            log.info("雷赛电机-上升完成-one");
                        });
                    }
                }, 100);
            }
            case 3 -> {
                datePointRespsAll.addAll(datePointResps);
                datePointResps = new ArrayList<>();
                lsCmdSendService.leisaiSetMoveDist("2", "01", motorDistance);
                scheduledFuture = taskScheduler1.scheduleWithFixedDelay(() -> {
                    if (motorLocation >= motorDistance - 100 && motorLocation <= motorDistance + 100) {
                        scheduledFuture.cancel(true);
                        DelayUtil.delayedExecution(1000, () -> {
                            nextIntMotor();
                            log.info("雷赛电机-下降完成-two");
                        });
                    }
                }, 100);

            }
            case 4 -> {
                datePointRespsAll.addAll(datePointResps);
                datePointResps = new ArrayList<>();
                lsCmdSendService.leisaiSetMoveDist("2", "01", modelZero);
                scheduledFuture = taskScheduler1.scheduleWithFixedDelay(() -> {
                    if (motorLocation >= modelZero -100 && motorLocation <= modelZero + 100) {
                        scheduledFuture.cancel(true);
                        DelayUtil.delayedExecution(1000, () -> {
                            nextIntMotor();
                            log.info("雷赛电机-上升完成-two");
                        });
                    }
                }, 100);
            }
            case 5 -> {
                byId.setProcessStep(0);
                processRecordsService.saveProcessDao(byId);

                datePointRespsAll.addAll(datePointResps);
                datePointResps = new ArrayList<>();
                siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0000");
                log.info("雷赛电机-运动完成");
                lsCmdSendService.cancelScheduledFuture();

                saveResp();
                /* 清空数据 */
                release();

                /* 发送数据出去 */
                callingInterfaces();
            }
            default -> {
                log.info("当前流程结束/出错");
            }
        }
    }

    public boolean calibrationIsRun = false,calibrationIsOk = false;
    List<Integer> plcValueList = new ArrayList<>();
    public int calibrationPlcValue = 999000;

    public void motorCalibration(){
        lsCmdSendService.leisaiSetMotorModel("2", "01", 1);

        lsCmdSendService.leisaiSetMoveDist("2", "01", 574000);
        DelayUtil.delayedExecution(8000, new Runnable() {
            @Override
            public void run() {
                lsCmdSendService.leisaiSetMoveDist("2", "01", 0);
                DelayUtil.delayedExecution(8000, new Runnable() {
                    @Override
                    public void run() {
                        OptionalDouble optionalAverage = plcValueList.stream()
                                .mapToDouble(Integer::doubleValue)
                                .average();

                        double v = optionalAverage.orElseThrow(() -> new IllegalStateException("Failed to calculate average"));
                        calibrationPlcValue = (int) v;
                        calibrationIsOk = true;
                        calibrationIsRun = false;
                    }
                });
            }
        });
    }

    public String workOrderNumber = "",powerStationName = "", intervalNumber = "";

    /**
     * 调用MES接口，上传测量结果
     */
    public void callingInterfaces(){
        String ip = "http://10.89.33.67:6867/mes/out_producer/outProducer/strengthResult";
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("X-Access-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MTc3NDM1NTUsInVzZXJuYW1lIjoibWVzMTI2LXpqIn0.3WOlmg9NiqUhWx8qqK_QIM-7vT6uMBHPT2fD5tCHUGg");

        if (workOrderNumber.isEmpty()){
            log.info("当前我还没有工单编号!!!");
            return;
        }
        Map<String, Object> params = new HashMap<>();
        params.put("pono", workOrderNumber);
        params.put("cust1", tdRunResultResp.getL1ValueNo1());
        params.put("cust2", tdRunResultResp.getL2ValueNo1());
        params.put("cust3", tdRunResultResp.getL3ValueNo1());
        params.put("cust4", tdRunResultResp.getNo_on3());
        params.put("cust5", tdRunResultResp.getNo_off3());
        params.put("cust6", tdRunResultResp.getNo_on4());
        params.put("cust7", tdRunResultResp.getNo_off4());
        try {
            HttpClientUtil.post(ip,params,headers);
        } catch (Exception e) {
//            throw new RuntimeException(e);
            log.error(e.getMessage());
        }
        //清空一下上一次的值
        workOrderNumber = "";
        powerStationName="";
        intervalNumber="";
    }

    public void saveResp() {
        /*
            获取公斤数
         */
        List<Integer> kilogram = new ArrayList<>();
        for (TensileDistanceResp tensileDistanceResp : memoryCompare) {
            kilogram.add(tensileDistanceResp.getTensileValue());
        }
        /* 公斤数 - 最大值，最小值 */
        Integer max = Collections.max(kilogram);
        Integer min = Collections.min(kilogram);

        /* 总数/个数 = 平均数 */
        Integer count = 0;
        for (Integer i : kilogram) {
            count += i;
        }
        int average = count / kilogram.size();
        mdResp.setKilogramMax(max);
        mdResp.setKilogramMin(min);
        mdResp.setKilogramAverage(average);


        EventRecords eventRecordsById = tensileDistanceService.findEventRecordsById(mdResp.getEventId());

        /* 获取四段运动数据 */
        Map<String, List<TensileDistanceResp>> respById = findRespById();

        /* -----以下为 刚合点 L值 的记录---- */
        /* 获取四段的十二个刚合点 */
        List<AllDatePoint> datePoint = findDatePoint(respById);
        /* 保存十二个刚合点时候的L值 */
        getValueL(datePoint);

        /* -----以下为 刚合点 开合 的记录---- */
        /* 获取四段的八个空开空合 */
        double[] datePointMax = findDatePointMax(respById);
        /* 保存 */
        getValueT(datePointMax);

        log.info("记录-刚合点相关保存成功");

        if ((max / 1000.00) <= 440 && (min / 1000.00 > -440)) {
            mdResp.setProductQualified("合格");
        } else {
            mdResp.setProductQualified("不合格");
        }

        if (
                mdResp.getL1ValueNo1() <= 300 || mdResp.getL2ValueNo1() <= 300 || mdResp.getL3ValueNo1() <= 300 ||
                mdResp.getL1ValueNo2() <= 300 || mdResp.getL2ValueNo2() <= 300 || mdResp.getL3ValueNo2() <= 300 ||
                mdResp.getL1ValueNo3() <= 300 || mdResp.getL2ValueNo3() <= 300 || mdResp.getL3ValueNo3() <= 300
        ){
            mdResp.setProductQualified("不合格");
        }

        eventRecordsById.setRecordResult(mdResp.getProductQualified());
        tensileDistanceService.updateEventRecords(eventRecordsById);

        BeanUtils.copyProperties(mdResp,tdRunResultResp);

        int mdId = tensileDistanceService.saveMeasurementData(mdResp);
        log.info("记录-中间表保存完成");
        for (TensileDistanceResp tensileDistanceResp : memoryCompare) {
            tensileDistanceResp.setMeasurementId(mdId);
            tensileDistanceResp.setWorkOrderNumber(workOrderNumber);
        }
        tensileDistanceService.saveTensileDistance(memoryCompare);
    }

    /**
     * 通过类型Id 获取 对应的List对象
     *
     * @return Maps
     */
    private Map<String, List<TensileDistanceResp>> findRespById() {
        Map<String, List<TensileDistanceResp>> map = new HashMap<>();
        for (TensileDistanceResp tensileDistanceResp : memoryCompare) {
            if (map.get(tensileDistanceResp.getType()) == null) {
                map.put(tensileDistanceResp.getType(), new ArrayList<>());
            }
            map.get(tensileDistanceResp.getType()).add(tensileDistanceResp);
        }
        return map;
    }

    /**
     * 获取刚合点 并且计算出 对应的L值
     *
     * @param map 根据类型获取的数据
     * @return L值数组
     */
    private List<AllDatePoint> findDatePoint(Map<String, List<TensileDistanceResp>> map) {
        List<AllDatePoint> allDatePoints = new ArrayList<>();
        for (String s : map.keySet()) {
            List<TensileDistanceResp> respList = map.get(s);
            int type = switch (s) {
                case "1" -> 1;
                case "2" -> 2;
                case "3" -> 3;
                case "4" -> 4;
                default -> -1;
            };
            AllDatePoint allDatePoint = new AllDatePoint();
            if (type == 1 || type == 3){
                List<DatePoint> onePoints = findOnePoints(respList);
                allDatePoint.setDatePoints(onePoints);
                allDatePoint.setRunTimes(type);
                allDatePoints.add(allDatePoint);
            } else if (type == 2 || type ==4){
                List<DatePoint> onePoints = findOnePoints2(respList);
                allDatePoint.setDatePoints(onePoints);
                allDatePoint.setRunTimes(type);
                allDatePoints.add(allDatePoint);
            }
        }
        log.info("keyset->{}" ,map.keySet());
        return allDatePoints;
    }

    private List<DatePoint> findOnePoints(List<TensileDistanceResp> respList) {
        List<DatePoint> datePoints = new ArrayList<>();
        for (TensileDistanceResp tensileDistanceResp : respList) {
            double v = ((tensileDistanceResp.getDistanceValue() / 10000.00) * 5) / 7;
            double l = (225 - 7 - 55.5 - v - 23);

            if (tensileDistanceResp.getDataPointA() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(0);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);

                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
            if (tensileDistanceResp.getDataPointB() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(1);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);
                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
            if (tensileDistanceResp.getDataPointC() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(2);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);
                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
        }
        log.info("findOnePoints-->{}",datePoints.toArray());
        return datePoints;
    }

    private List<DatePoint> findOnePoints2(List<TensileDistanceResp> respList) {
        List<DatePoint> datePoints = new ArrayList<>();
        for (TensileDistanceResp tensileDistanceResp : respList) {
            double v = ((tensileDistanceResp.getDistanceValue() / 10000.00) * 5) / 7;
            double l = (225 - 7 - 55.5 - v - 23 - 44);
            if (tensileDistanceResp.getDataPointA() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(0);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);

                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
            if (tensileDistanceResp.getDataPointB() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(1);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);
                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
            if (tensileDistanceResp.getDataPointC() == 1) {
                DatePoint datePoint = new DatePoint();
                /* 0 为 A 1 为 B 2 为C  */
                datePoint.setType(2);
                datePoint.setDistance(v);
                datePoint.setTensileValue(tensileDistanceResp.getTensileValue());
                try {
                    datePoint.setRunTimes(Integer.parseInt(tensileDistanceResp.getType()));
                }catch (NumberFormatException numberFormatException){
                    datePoint.setRunTimes(-1);
                }
                datePoint.setLValue(l);
                datePoint.setTime(tensileDistanceResp.getNowLongTime());
                datePoint.setMeasurementId(tensileDistanceResp.getMeasurementId());
                datePoints.add(datePoint);
            }
        }
        log.info("findOnePoints-->{}",datePoints.toArray());
        return datePoints;
    }

    /**
     * 获取每一段刚合点的最大值
     *
     * @param respById map分类数组
     */
    private double[] findDatePointMax(Map<String, List<TensileDistanceResp>> respById) {
        double[] points = new double[8];
        for (String s : respById.keySet()) {
            List<TensileDistanceResp> respList = respById.get(s);
            int type = switch (s) {
                case "1" -> 1;
                case "2" -> 2;
                case "3" -> 3;
                case "4" -> 4;
                default -> -1;
            };
            double[] pointTwoMax = new double[2];
            if (type == 1 || type == 3){
                pointTwoMax = findPointTwoMax(respList);
            } else if(type == 2 || type ==4){
                pointTwoMax = findPointTwoMin(respList);
            }
            if (type != -1){
                try{
                    System.arraycopy(pointTwoMax, 0, points, (type - 1) * 2, pointTwoMax.length);
                }catch (ArrayIndexOutOfBoundsException ignored){
                    log.info("当前下标异常---");
                }
            }
        }
        return points;
    }

    private double[] findPointTwoMin(List<TensileDistanceResp> respList) {
        Collections.reverse(respList);
        double[] maxPoint = new double[2];
        double minBeforePoint = Double.POSITIVE_INFINITY; // 初始化为正无穷大
        double minAfterPoint = Double.POSITIVE_INFINITY;  // 初始化为正无穷大
        boolean foundPoint = false; // 标志位，用于跟踪是否找到了DataPointA/B/C等于1的点

        for (TensileDistanceResp tensileDistanceResp : respList) {
            double tensileValue = tensileDistanceResp.getTensileValue();
            if (!foundPoint && tensileValue < minBeforePoint) {
                minBeforePoint = tensileValue; // 更新找到点之前的最大值
            }
            if (foundPoint && tensileValue < minAfterPoint) {
                minAfterPoint = tensileValue; // 更新找到点之后的最大值
            }
            if (tensileDistanceResp.getDataPointA() == 1 || tensileDistanceResp.getDataPointB() == 1 || tensileDistanceResp.getDataPointC() == 1) {
                foundPoint = true; // 标记已经找到了DataPointA/B/C等于1的点
            }
        }

        // 如果没有找到DataPointA/B/C等于1的点，则将两个值都设为0
        if (!foundPoint) {
            minBeforePoint = 999000;
            minAfterPoint = 999000;
        }

        maxPoint[0] = minBeforePoint / 1000.00; // 转换单位为千
        maxPoint[1] = minAfterPoint / 1000.00;  // 转换单位为千
        log.info("maxBefore->{},minAfter->{},", maxPoint[0], maxPoint[1]);
        return maxPoint;
    }

    private double[] findPointTwoMax(List<TensileDistanceResp> respList) {
        Collections.reverse(respList);
        double[] maxPoint = new double[2];
        double maxBeforePoint = Double.NEGATIVE_INFINITY; // 初始化为负无穷大
        double maxAfterPoint = Double.NEGATIVE_INFINITY;  // 初始化为负无穷大
        boolean foundPoint = false; // 标志位，用于跟踪是否找到了DataPointA/B/C等于1的点

        for (TensileDistanceResp tensileDistanceResp : respList) {
            double tensileValue = tensileDistanceResp.getTensileValue();
            if (!foundPoint && tensileValue > maxBeforePoint) {
                maxBeforePoint = tensileValue; // 更新找到点之前的最大值
            }
            if (foundPoint && tensileValue > maxAfterPoint) {
                maxAfterPoint = tensileValue; // 更新找到点之后的最大值
            }
            if (tensileDistanceResp.getDataPointA() == 1 || tensileDistanceResp.getDataPointB() == 1 || tensileDistanceResp.getDataPointC() == 1) {
                foundPoint = true; // 标记已经找到了DataPointA/B/C等于1的点
            }
        }

        // 如果没有找到DataPointA/B/C等于1的点，则将两个值都设为0
        if (!foundPoint) {
            maxBeforePoint = 999000;
            maxAfterPoint = 999000;
        }

        maxPoint[0] = maxBeforePoint / 1000.00; // 转换单位为千
        maxPoint[1] = maxAfterPoint / 1000.00;  // 转换单位为千
        log.info("maxBefore->{},maxAfter->{},", maxPoint[0], maxPoint[1]);
        return maxPoint;
    }


    /**
     * 获取报警信息
     */
    public void getAlarmMessage() {
        lsCmdSendService.leisaiReadAlarmMessage("2", "01", s -> {
            /* 判断报警信息 */
            switch (s) {
                case "0000" -> {
                    log.info("电机报警-当前电机正常运行中" + s);
                    isWarnStatus = false;
                    warnList.replace(0, 5, "10000");
                    log.info("自检-当前无报警");
                }
                case "00E0" -> {
                    isWarnStatus = true;
                    warnList.replace(0, 1, "0");
                    warnList.replace(1, 2, "1");
                    siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0200");
                    log.info("电机报警-当前电机过流-00E0" + s);
                }
                case "00E1" -> {
                    isWarnStatus = true;
                    warnList.replace(0, 1, "0");
                    warnList.replace(1, 2, "1");
                    siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0200");
                    log.info("电机报警-当前电机过流-00E1" + s);
                }

                case "0100" -> {
                    isWarnStatus = true;
                    warnList.replace(0, 1, "0");
                    warnList.replace(2, 3, "1");
                    siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0200");
                    log.info("电机报警-当前电机过载" + s);
                }
                case "0190" -> {
                    isWarnStatus = true;
                    warnList.replace(0, 1, "0");
                    warnList.replace(3, 4, "1");
                    siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0200");
                    log.info("电机报警-当前电机抖动幅度过大" + s);
                }

                case "00C0" -> {
                    isWarnStatus = true;
                    warnList.replace(0, 1, "0");
                    warnList.replace(4, 5, "1");
                    siemensReceiveHandelDao.siemensWriteValue("0000", "1", "0000", "0200");
                    log.info("电机报警-当前电机过压" + s);
                }
                default -> log.info("当前报警的值为" + s);
            }
            motorSelfCheck = true;
            tdRespSse.setWarningStatus(isWarnStatus);
            tdRespSse.setWarnInfo(warnList.toString());
            log.info("通讯-雷赛电机通讯正常");
        });
    }

    public void compareStatus(int temp) {
        /* 自检开启关闭 */
        if (isSelfChecking) {
            final int[] timeout = {1000};
            log.info("自检-开始读取自检内容");
            ScheduledFuture<?> scheduledFuture1 = taskScheduler1.scheduleWithFixedDelay(() -> {
                timeout[0]++;
                switch (temp) {
                    case 0 -> {
                        /* 电池通讯正常 */
                        if (batterySelfCheck) {
                            contentStep = 1;
                            tdRespSse.setSelfCheckStep(contentStep);
                            mapSF.get("selfChecking").cancel(true);
                            mapSF.remove("selfChecking");
                            compareStatus(1);
                        }
                        log.info("电池-通讯异常");
                    }
                    case 1 -> {
                        /* 电池通讯正常 */
                        if (plcSelfCheck) {
                            contentStep = 2;
                            tdRespSse.setSelfCheckStep(contentStep);
                            mapSF.get("selfChecking").cancel(true);
                            mapSF.remove("selfChecking");
                            compareStatus(2);
                        }
                        log.info("plc-通讯异常");
                    }
                    case 2 -> {
                        /* 电池通讯正常 */
                        if (motorSelfCheck) {
                            contentStep = 3;
                            tdRespSse.setSelfCheckStep(contentStep);
                            mapSF.get("selfChecking").cancel(true);
                            mapSF.remove("selfChecking");
                            compareStatus(3);
                        }
                        log.info("电机-通讯异常");
                    }
                    case 3 -> {
                        /* 电池通讯正常 */
                        if (!isWarnStatus) {
                            contentStep = 4;
                            tdRespSse.setSelfCheckStep(contentStep);
                            SelfCheckingOK = true;
                            tdRespSse.setSelfCheckOK(SelfCheckingOK);
                            mapSF.get("selfChecking").cancel(true);
                            mapSF.remove("selfChecking");
                        }
                        log.info("报警-当前有报警");
                    }
                }
                if (timeout[0] == 1000) {
                    mapSF.get("selfChecking").cancel(true);
                    mapSF.remove("selfChecking");
                    tdRespSse.setSelfCheckStep(-999 + (temp * 1000));
                    log.info("当前自检超时");
                }
            }, 100);
            mapSF.put("selfChecking", scheduledFuture1);
        }
    }

    /**
     * 保存L值数组到对象中
     *
     * @param datePoint L数组
     */
    private void getValueL(List<AllDatePoint> datePoint) {

        for (AllDatePoint allDatePoint : datePoint) {
            int runTimes = allDatePoint.getRunTimes();
            if (runTimes == 1){
                for (DatePoint point : allDatePoint.getDatePoints()) {
                    if (point.getType() == 0) {
                        mdResp.setL1ValueNo1(point.getLValue());
                    } else if (point.getType() == 1) {
                        mdResp.setL2ValueNo1(point.getLValue());
                    } else if (point.getType() == 2) {
                        mdResp.setL3ValueNo1(point.getLValue());
                    }
                }
            } else if (runTimes == 2){
                for (DatePoint point : allDatePoint.getDatePoints()) {
                    if (point.getType() == 0) {
                        mdResp.setL1ValueNo2(point.getLValue());
                    } else if (point.getType() == 1) {
                        mdResp.setL2ValueNo2(point.getLValue());
                    } else if (point.getType() == 2) {
                        mdResp.setL3ValueNo2(point.getLValue());
                    }
                }
            } else if (runTimes == 3){
                for (DatePoint point : allDatePoint.getDatePoints()) {
                    if (point.getType() == 0) {
                        mdResp.setL1ValueNo3(point.getLValue());
                    } else if (point.getType() == 1) {
                        mdResp.setL2ValueNo3(point.getLValue());
                    } else if (point.getType() == 2) {
                        mdResp.setL3ValueNo3(point.getLValue());
                    }
                }
            } else if (runTimes == 4){
                for (DatePoint point : allDatePoint.getDatePoints()) {
                    if (point.getType() == 0) {
                        mdResp.setL1ValueNo4(point.getLValue());
                    } else if (point.getType() == 1) {
                        mdResp.setL2ValueNo4(point.getLValue());
                    } else if (point.getType() == 2) {
                        mdResp.setL3ValueNo4(point.getLValue());
                    }
                }
            }
        }

    }

    private void getValueT(double[] datePointMax) {
        for (int i = 0; i < datePointMax.length; i++) {
            switch (i) {
                case 0 -> {
                    mdResp.setNo_on1(datePointMax[i]);
                }
                case 1 -> {
                    mdResp.setNo_off1(datePointMax[i]);
                }
                case 2 -> {
                    mdResp.setNo_on2(datePointMax[i]);
                }
                case 3 -> {
                    mdResp.setNo_off2(datePointMax[i]);
                }
                case 4 -> {
                    mdResp.setNo_on3(datePointMax[i]);
                }
                case 5 -> {
                    mdResp.setNo_off3(datePointMax[i]);
                }
                case 6 -> {
                    mdResp.setNo_on4(datePointMax[i]);
                }
                case 7 -> {
                    mdResp.setNo_off4(datePointMax[i]);
                }
            }
        }
    }

    /*----------------------------------------------------------------------------------------*/

    private void setLValueToSql() {
        for (DatePointResp datePointResp : datePointRespsAll) {
            int typeDec = Integer.parseInt(datePointResp.getType());
            if (typeDec == 1) {
                setLValues(1, datePointResp);
            } else if (typeDec == 2) {
                setLValues(2, datePointResp);
            } else if (typeDec == 3) {
                setLValues(3, datePointResp);
            } else if (typeDec == 4) {
                setLValues(4, datePointResp); // 假设逻辑与typeDec == 3相同
            }
        }
    }


    private void setLValues(int typeGroup, DatePointResp datePointResp) {
        if (datePointResp.getDataPointA() != 0) {
            switch (typeGroup) {
                case 1:
                    mdResp.setL1ValueNo1((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 2:
                    mdResp.setL1ValueNo2((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 3:
                    mdResp.setL1ValueNo3((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                default:
                    break;
            }
        } else if (datePointResp.getDataPointB() != 0) {
            switch (typeGroup) {
                case 1:
                    mdResp.setL2ValueNo1((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 2:
                    mdResp.setL2ValueNo2((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 3:
                    mdResp.setL2ValueNo3((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                default:
                    break;
            }
        } else if (datePointResp.getDataPointC() != 0) {
            switch (typeGroup) {
                case 1:
                    mdResp.setL3ValueNo1((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 2:
                    mdResp.setL3ValueNo2((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                case 3:
                    mdResp.setL3ValueNo3((((datePointResp.getDistanceValue() / 10000.00) * 5) / 7));
                    break;
                default:
                    break;

            }

        }

    }


    private double[] findDatePointMaxValue(Map<String, List<TensileDistanceResp>> respById, Map<Integer, DatePointResp> maxValueT) {
        double[] points = new double[8];
        for (Integer i : maxValueT.keySet()) {
            for (String s : respById.keySet()) {
                if (i == Integer.parseInt(s)) {
                    DatePointResp datePointResp = maxValueT.get(i);
                    List<TensileDistanceResp> tensileDistanceResps = respById.get(s);
                    double[] twoDatePointMax = findTwoDatePointMax(datePointResp, tensileDistanceResps);
                    points[ (i - 1) * 2 ] = twoDatePointMax[0];
                    points[ (i - 1) * 2 + 1 ] = twoDatePointMax[1];
                }
            }
        }
        return points;
    }



    private double[] findTwoDatePointMax(DatePointResp datePointResp, List<TensileDistanceResp> tensileDistanceResps) {
        int beforeMax = Integer.MIN_VALUE;
        int afterMax = Integer.MIN_VALUE;
        double[] points = new double[2];
        for (TensileDistanceResp tensileDistanceResp : tensileDistanceResps) {
            if (tensileDistanceResp.getDistanceValue() < datePointResp.getDistanceValue()) {
                if (tensileDistanceResp.getTensileValue() > beforeMax) {
                    beforeMax = tensileDistanceResp.getTensileValue();
                }
            } else {
                if (tensileDistanceResp.getTensileValue() > afterMax) {
                    afterMax = tensileDistanceResp.getTensileValue();
                }
            }
        }
        points[0] = beforeMax;
        points[1] = afterMax;
        return points;
    }


    private Map<Integer, DatePointResp> findMaxValueT() {

        Map<Integer, DatePointResp> map = new HashMap<>();
        for (DatePointResp datePointResp : datePointRespsAll) {
            int typeDec = Integer.parseInt(datePointResp.getType());
            if (typeDec == 1 || typeDec == 3) {
                DatePointResp minTensileResp = findMinTensileValue(datePointRespsAll, typeDec);
                if (minTensileResp != null) {
                    map.put(typeDec, minTensileResp);
                }
            } else if (typeDec == 2 || typeDec == 4) {
                // 寻找distanceValue最大的DatePointResp
                DatePointResp maxDistanceResp = findMaxDistanceValue(datePointRespsAll, typeDec);
                if (maxDistanceResp != null) {
                    map.put(typeDec, maxDistanceResp);
                }
            }
        }
        return map;
    }

    /**
     *  空开空合  实开实合
     */
    private DatePointResp findMinTensileValue(List<DatePointResp> list, int typeDec) {
        DatePointResp minTensileResp = null;
        int minTensileValue = Integer.MAX_VALUE;
        for (DatePointResp pointResp : list) {
            int type = Integer.parseInt(pointResp.getType());
            if (type == typeDec) {
                int tensileValue = (int) pointResp.getTensileValue();
                if (tensileValue < minTensileValue) {
                    minTensileValue = tensileValue;
                    minTensileResp = pointResp;
                }
            }
        }
        return minTensileResp;

    }

    private DatePointResp findMaxDistanceValue(List<DatePointResp> list, int typeDec) {
        DatePointResp maxDistanceResp = null;
        int maxDistanceValue = Integer.MIN_VALUE;
        for (DatePointResp pointResp : list) {
            int type = Integer.parseInt(pointResp.getType());
            if (type == typeDec) {
                int distanceValue = (int) pointResp.getDistanceValue();
                if (distanceValue > maxDistanceValue) {
                    maxDistanceValue = distanceValue;
                    maxDistanceResp = pointResp;
                }
            }
        }
        return maxDistanceResp;
    }


}
//
//
//        /*--------------------------以下为测试部分----------------------------------*/
//        public double plcValue11 = 0,motorValue11 = 0;
//
//public boolean testStatus = true;
//public String testType = "1";
//        public int ad1=0,ad2=0,ad3=0;
//        public int ad1Last =0,ad2Last=0,ad3Last=0;
//public void initTest(){
//
//    taskScheduler1.scheduleWithFixedDelay(new Runnable() {
//        @Override
//        public void run() {
//            if (testStatus){
//                LocalDateTime localDateTime = LocalDateTime.now();
//                String format = localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
//                TensileDistanceSseResp tensileDistanceSseResp = new TensileDistanceSseResp();
//                tensileDistanceSseResp.setDistanceValue(motorValue11);
//                tensileDistanceSseResp.setTensileValue(plcValue11);
//                tensileDistanceSseResp.setDataPointA(0);
//                tensileDistanceSseResp.setDataPointB(0);
//                tensileDistanceSseResp.setDataPointC(0);
//                tensileDistanceSseResp.setType(testType);
//                tensileDistanceSseResp.setNowTime(format);
//                tensileDistanceSseResp.setMeasurementId(1);
//                tdRespSse = tensileDistanceSseResp;
//            }
//        }
//    },200);
//    taskScheduler1.scheduleWithFixedDelay(new Runnable() {
//        @Override
//        public void run() {
//            if (testStatus){
//                motorValue11 += 20.00;
//                plcValue11 += 1.50;
//
//                if (motorValue11 == 2400){
//                    testType = "2";
//                    datePointResps = new ArrayList<>();
//                } else if (motorValue11 == 4800){
//                    testType = "3";
//                    datePointResps = new ArrayList<>();
//                } else if (motorValue11 == 7200){
//                    testType = "4";
//                    datePointResps = new ArrayList<>();
//                } else if (motorValue11 == 9600){
//                    testType = "1";
//                    datePointResps = new ArrayList<>();
//                    motorValue11 = 0;
//                    plcValue11 = 0;
//                    testStatus = false;
//                }
//            }
//        }
//    },200);
//    taskScheduler1.scheduleWithFixedDelay(new Runnable() {
//        @Override
//        public void run() {
//            if (testStatus){
//                /* 三个刚合点的状态-> 0800  0C00 0E00 */
//                DatePointResp datePointResp = new DatePointResp();
//                /* 只要有一个刚合点为1，则判断 */
//                if (ad1 == 1) {
//                    if (ad1Last == 0) {
//                        ad1Last = 1;
//                        datePointResp.setDataPointA(1);
//                        extracted(datePointResp);
//                    }
//                } else {
//                    if (ad1Last == 1) {
//                        ad1Last = 0;
//                        ad1 = 0;
//                        datePointResp.setDataPointA(1);
//                        extracted(datePointResp);
//                    }
//                }
//                if (ad2 == 1) {
//                    if (ad2Last == 0) {
//                        ad2Last = 1;
//                        datePointResp.setDataPointB(1);
//                        extracted(datePointResp);
//                    }
//                } else {
//                    if (ad2Last == 1) {
//                        ad2Last = 0;
//                        ad2 = 0;
//                        datePointResp.setDataPointB(1);
//                        extracted(datePointResp);
//                    }
//                }
//                if (ad3 == 1) {
//                    if (ad3Last == 0) {
//                        ad3Last = 1;
//                        datePointResp.setDataPointC(1);
//                        extracted(datePointResp);
//                    }
//                } else {
//                    if (ad3Last == 1) {
//                        ad3Last = 0;
//                        ad3 = 0;
//                        datePointResp.setDataPointC(1);
//                        extracted(datePointResp);
//                    }
//                }
//            }
//        }
//    },100);
//}
///*--------------------------以上为测试部分----------------------------------*/

